/**
 * 
 */
package com.ermax.aircond.report.web.bean;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ermax.aircond.common.service.ReadMachineDataService;
import com.ermax.aircond.common.service.WriteMachineDataService;
import com.ermax.aircond.manage.domain.RealTimeControl;
import com.ermax.aircond.report.domain.CommandCheck;
import com.ermax.aircond.report.domain.CommandCheckDisplay;
import com.ermax.aircond.report.domain.ErrorDetail;
import com.ermax.aircond.report.service.AuditLogService;
import com.ermax.aircond.resource.MessageBundle;
import com.ermax.aircond.util.service.MachineCommandService;
import com.ermax.aircond.util.web.bean.DataTableBean;

/**
 * @author Eric
 *
 */
@Scope("view")
@Component
public class IneffectiveMachineBean extends DataTableBean implements
		Serializable {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 3663876937483077754L;
	private static final Logger logger = LoggerFactory.getLogger(IneffectiveMachineBean.class);
	private static final DateFormat DATA_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
	
	@Resource(name = "writeMachineDataService")
	private WriteMachineDataService writeMachineDataService;
	
	@Resource(name = "machineCommandService")
	private MachineCommandService machineCommandService;	
	
	private List<CommandCheck> commandCheckList;
	private List<CommandCheckDisplay> commandCheckDisplayList;
	
	@Resource(name = "auditLogService")
	private AuditLogService auditLogService;
	
	@PostConstruct
	public void init() {
		try {
			reset();
		} catch (Exception ex) {
			String message = MessageBundle.getInstance().getMessage("error_init_fail", FacesContext.getCurrentInstance().getViewRoot().getLocale());
			FacesMessage facesMessage = new FacesMessage(message);
			FacesContext.getCurrentInstance().addMessage(null, facesMessage);
		}
	}
	
	private void reset() throws Exception {
		commandCheckList = writeMachineDataService.findLatestMachineData();
		commandCheckDisplayList = new ArrayList<CommandCheckDisplay>();
		
		for (CommandCheck commandCheck : commandCheckList) {
			
			RealTimeControl realTimeControl = new RealTimeControl();
			RealTimeControl currentControl = new RealTimeControl();
			CommandCheckDisplay commandCheckDisplay = castToSub(commandCheck);

			List<String> values = machineCommandService.extractMachineData(commandCheck.getCmd());
			for(int j=0; j<values.size(); j++) {
				realTimeControl = machineCommandService.translateCommand(realTimeControl, values.get(j));
			}
			
			values = machineCommandService.extractMachineData(commandCheck.getCurrentCmd());
			for(int j=0; j<values.size(); j++) {
				currentControl = machineCommandService.translateCommand(realTimeControl, values.get(j));
			}		
			
			commandCheckDisplay.setRealTimeControl(realTimeControl);
			commandCheckDisplay.setCurrentControl(currentControl);
			commandCheckDisplayList.add(commandCheckDisplay);
		}
	}
	
	public void genExcel(ActionEvent event) throws Exception {
		Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
		HSSFWorkbook workbook = auditLogService.convertIneffectiveMachinestoExcel(getCommandCheckDisplayList(), locale);
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
		response.reset();

		StringBuilder sbHeader = new StringBuilder();
		sbHeader.append("attachment; filename=\"");
		sbHeader.append("INEFFECTIVE_REPORT_");
		sbHeader.append(DATA_FORMAT.format(new Date()));
		sbHeader.append("_");
		sbHeader.append(".xls\"");

		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", sbHeader.toString());

		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		FacesContext.getCurrentInstance().responseComplete();
	}

	
	public List<CommandCheckDisplay> getCommandCheckDisplayList() {
		return commandCheckDisplayList;
	}

	public void setCommandCheckDisplayList(List<CommandCheckDisplay> commandCheckDisplayList) {
		this.commandCheckDisplayList = commandCheckDisplayList;
	}
	
	private CommandCheckDisplay castToSub(CommandCheck commandCheck) {
		
		CommandCheckDisplay commandCheckDisplay = new CommandCheckDisplay();
		
		commandCheckDisplay.setCmd(commandCheck.getCmd());
		commandCheckDisplay.setCmdTime(commandCheck.getCmdTime());
		commandCheckDisplay.setCurrentCmd(commandCheck.getCurrentCmd());
		commandCheckDisplay.setNid(commandCheck.getNid());
		commandCheckDisplay.setRev(commandCheck.getRev());
		
		return commandCheckDisplay;		
	}
	
}
